package top.huhuiyu.springboot.study.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.huhuiyu.springboot.study.base.BaseDataResult;
import top.huhuiyu.springboot.study.base.BaseResult;
import top.huhuiyu.springboot.study.base.PageBean;
import top.huhuiyu.springboot.study.entity.SoftwareType;
import top.huhuiyu.springboot.study.entity.TestEntity;
import top.huhuiyu.springboot.study.exception.AppException;
import top.huhuiyu.springboot.study.service.SoftwareTypeService;
import top.huhuiyu.springboot.study.validate.CommonValidator;

import java.util.List;

/**
 * @author 胡辉煜
 */
// @Controller +  @ResponseBody = @RestController
@Controller
@RequiredArgsConstructor
public class IndexController {
  private final SoftwareTypeService softwareTypeService;

  @RequestMapping("")
  @ResponseBody
  public BaseResult index() {
    return BaseResult.ok("欢迎使用黑暗骑士的后端接口");
  }

  @RequestMapping("/test/data")
  public String data(String name, Model model) {
    // 通过model传递数据到页面
    name = StringUtils.hasText(name) ? name : "匿名";
    model.addAttribute("username", name);
    List<SoftwareType> list = softwareTypeService.query(new SoftwareType(), PageBean.instance(1, 10)).getData().getData();
    model.addAttribute("list", list);

    // 返回值就是模板目录中的文件名称，不需要扩展名，默认为html
    return "data";
  }

  @GetMapping("/test/exception")
  @ResponseBody
  public BaseResult exception(String info) {
    // 如果传递了info就抛出异常，终止执行
    if (StringUtils.hasText(info)) {
      throw AppException.getInstance(info);
    }
    return BaseResult.ok("没有异常");
  }

  @GetMapping("/test/exception2")
  @ResponseBody
  public BaseResult exception2(String age) {
    return BaseResult.ok(String.format("年龄信息:%s", Integer.parseInt(age)));
  }

  @ResponseBody
  @RequestMapping("/test/validate")
  public BaseDataResult<TestEntity> validate(
      @RequestBody @Validated({CommonValidator.Add.class}) TestEntity entity) {
    return BaseDataResult.ok(entity);
  }

  @ResponseBody
  @RequestMapping("/test/validate2")
  public BaseDataResult<TestEntity> validate2(
      @RequestBody @Validated({CommonValidator.Update.class}) TestEntity entity) {
    return BaseDataResult.ok(entity);
  }


}
